
const websocket = require('socket.io')
const UserLogin = require('../model/UserLogin')
const http = require('http')
const axios = require('axios')

let socketIO = null
const localKey = 'hmlgnb' // 用于记录本地服务的特殊标记
const socketPool = {} // socket对象池
let socketObj = null
module.exports.start = (server) => {
    socketIO = websocket(server, { transports: ['websocket'] })
    socketIO.on('connection', async function (socket) {
        socketObj = socket
        console.log("黑马头条-小智同学通讯开始连接!")
        var token = socket.request._query.token // 获取用户id
        if (socket.request._query.key === localKey) {
            // 特殊标记
            socketPool[localKey] = socketPool[localKey] || []
            socketPool[localKey].push(socket.id)
        } else {
            if (token) {
                const lgPeople = await UserLogin.findOne({ token }).lean()
                if (lgPeople) {
                    socketPool[lgPeople.user_id] = socket.id
                    console.log("验证通过token验证")
                } else {
                    console.log("没有找到对应的登录记录, 主动断开连接")
                    // socket.emit('disconnect')
                }
            } else {
                console.log("黑马头条-小智同学验证token没有传递, 主动断开连接")
                // socket.emit('disconnect')
            }
        }
        socket.on('message', async function (obj) {
            console.log("有人对小智说:" + obj.msg)
            try {
                const { data: { content } } = await axios({
                    url: 'http://api.qingyunke.com/api.php',
                    params: { key: 'free', appid: 0, msg: obj.msg }
                })
                socket.emit('message', { msg: content, timestamp: new Date().getTime() })
            } catch (error) {
                socket.emit('message', { msg: '你把小智整不会了,你真有点小可爱哦', timestamp: new Date().getTime() })
            }
        });
        socket.on('send', async function (msg) {
            console.log("有人对小智说:" + msg)
            try {
                const { data: { content } } = await axios({
                    url: 'http://api.qingyunke.com/api.php',
                    params: { key: 'free', appid: 0, msg }
                })
                socket.emit('message', content)
            } catch (error) {
                socket.emit('message', '你把小智整不会了,你真有点小可爱哦')
            }
        });
        socket.on('disconnect', function () {
            console.log("黑马头条-小智同学通讯断开!")
            if (socketPool[localKey] && socketPool[localKey].length) {
                socketPool[localKey] = socketPool[localKey].filter(item => item !== socket.id)
            }
        });
        socket.on('toOther', async function (msg) {
            // 对所有人说话
            socketIO.emit("toOther", msg)
        })
    });
}

// 给某人发消息
module.exports.sendMessageByUserId = (user_id, type, message) => {
    if (!socketPool[user_id]) {
        console.log("该socket消息已断开连接!")
        return
    }
    socketObj.broadcast.to(socketPool[user_id]).emit(type, message) // 给指定的某人发消息
}
// 群发消息
module.exports.sendLocalMessage = (type, message) => {
    socketIO.emit(type, message)
}
// 发送本地服务消息
module.exports.sendLocalMessage = (type, message) => {
    if (socketPool[localKey] && socketPool[localKey].length) {
        const localList = socketPool[localKey]
        localList.forEach(id => {
            const obj = socketIO.sockets.sockets.get(id)
            if (obj) {
                obj.emit(type, message)// 给指定的某人发消息
            }
        });
    } else {
        console.log("无法连接本地服务")
    }
}

module.exports.sendCurrentPeople = () => {
    // 发送当前实时在线人数
    socketIO.emit("current", socketPool[localKey] ? socketPool[localKey].length : 0)
}